package com.seari.gena.ciosClient.handler;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.seari.utils.JedisPoolUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import redis.clients.jedis.Jedis;

public class CIOSNotifyServerHandler extends ChannelInboundHandlerAdapter {

	Jedis jedis = JedisPoolUtils.getJedis();

	/**
	 * 当客户端主动链接服务端的链接后，这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
	 */
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().localAddress().toString() + " 通道已激活！");
	}

	/**
	 * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
	 */
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃！");
		// 关闭流

	}

	/**
	 * 功能: 此处用来处理收到的数据中含有中文的时 出现乱码的问题
	 */
	private String getMessage(ByteBuf buf) {
		byte[] con = new byte[buf.readableBytes()];
		buf.readBytes(con);
		try {
			return new String(con, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 功能：读取服务器发送过来的信息
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		String rev = getMessage(buf);
		System.out.println("客户端收到服务器数据:" + rev);
		ctx.writeAndFlush("HTTP/1.1 200 OK\r\n" + "Content-Length:0\r\n" + "\r\n");
		String xml = rev.split("\\r\\n\\r\\n")[1];
		List list = CIOSNotifyServerHandler.releaseXML(xml);
		jedis.hmset((String) list.get(0), (Map)list.get(1));
		
	}

	/**
	 * 功能：读取完毕客户端发送过来的数据之后的操作
	 */
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		System.out.println("服务端接收数据完毕");
	}

	/**
	 * 功能：服务端发生异常的操作
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		System.out.println("异常信息：\r\n" + cause.getMessage());
	}
	
	public static List releaseXML(String xml) {
		List retList = new ArrayList<>();
		Map<String, String> flagMap = new LinkedHashMap<String, String>();

		try {
			Document doc = null;
			try {
				doc = DocumentHelper.parseText(xml);
				// System.out.println(xml);
			} catch (DocumentException e2) {
				System.out.println("解析异常！返回信息格式错误");
				e2.printStackTrace();
			}
			Element root = doc.getRootElement();// 指向根节点
			// 单行，没有下层节点
			Iterator it = root.elementIterator();
			while (it.hasNext()) {
				Element element = (Element) it.next();
				Iterator attrIt = element.attributeIterator();
				String trainInfo = "";
				while (attrIt.hasNext()) {
					Attribute a = (Attribute) attrIt.next();
					trainInfo = trainInfo + a.getValue() + "_";
				}
				retList.add(trainInfo.substring(0, trainInfo.length()-1));
				Iterator eleIt = element.elementIterator();
				while (eleIt.hasNext()) {
					Element e = (Element) eleIt.next();
					if (!"".equals(e.getText().trim())) {
						flagMap.put(e.getName(), e.getText());
					}
					Iterator ite = e.elementIterator();
					while (ite.hasNext()) {
						Element ele = (Element) ite.next();
						flagMap.put(e.getName() + "_" + ele.getName(), ele.getText());
					}
				}
				retList.add(flagMap);
			}
			return retList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}